package com.iemes.controller.workcenter_model;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iemes.annotation.SystemLog;
import com.iemes.controller.index.BaseController;
import com.iemes.entity.NcCodeFormMap;
import com.iemes.entity.NcCodeGroupFormMap;
import com.iemes.entity.NcCodeGroupRelationFormMap;
import com.iemes.exception.BusinessException;
import com.iemes.mapper.base.BaseMapper;
import com.iemes.service.workcenter_model.NcCodeGroupService;
import com.iemes.util.Common;
import com.iemes.util.DateUtils;
import com.iemes.util.ListUtils;
import com.iemes.util.ResponseHelp;
import com.iemes.util.ShiroSecurityHelper;

/**
 * 
 */
@Controller
@RequestMapping("/workcenter_model/nc_code_group/")
public class NcCodeGroupController extends BaseController {

	@Inject
	private BaseMapper baseMapper;

	@Inject
	private NcCodeGroupService ncCodeGroupService;

	private Logger log = Logger.getLogger(this.getClass());
	private String ncCodeGroupMaintenanceUrl = Common.BACKGROUND_PATH
			+ "/workcenter_model/nc_code_group/nc_code_group_maintenance";

	// 页面跳转
	@RequestMapping("nc_code_group_maintenance")
	public String Get_nc_code_maintenance_Url(Model model,HttpServletRequest request) throws Exception {
		model.addAttribute("res", findByRes());
		String siteId = ShiroSecurityHelper.getSiteId();
		getNcCodeBindData(model, siteId, "");
		handlePageRes(model,request);
		return ncCodeGroupMaintenanceUrl;
	}

	private void getNcCodeBindData(Model model, String siteId, String ncCodeGroupId) {
		// 1.已分配不良代码组的不良代码列表
		// 查询不良代码组的不良代码信息
		List<NcCodeFormMap> listSelectedNcCodeFormMap = new ArrayList<NcCodeFormMap>();
		if (!StringUtils.isEmpty(ncCodeGroupId)) {
			NcCodeGroupRelationFormMap ncCodeGroupRelationFormMap = new NcCodeGroupRelationFormMap();
			ncCodeGroupRelationFormMap.put("nc_code_group_id", ncCodeGroupId);
			ncCodeGroupRelationFormMap.put("orderby", " order by create_time ");
			List<NcCodeGroupRelationFormMap> listNcCodeGroupRelationFormMap = new ArrayList<>();
			listNcCodeGroupRelationFormMap = baseMapper.findByNames(ncCodeGroupRelationFormMap);

			// 如果有不良代码，再查询不良代码的详细信息
			if (ListUtils.isNotNull(listNcCodeGroupRelationFormMap)) {
				for (int i = 0; i < listNcCodeGroupRelationFormMap.size(); i++) {
					NcCodeGroupRelationFormMap map = listNcCodeGroupRelationFormMap.get(i);
					String ncCodeId = map.getStr("nc_code_id");
					List<NcCodeFormMap> listNcCodeFormMap = baseMapper.findByAttribute("id", ncCodeId,
							NcCodeFormMap.class);
					if (!ListUtils.isNotNull(listNcCodeFormMap)) {
						String errMsg = "未查询到不良代码ID" + ncCodeId + "的详细信息，请确定该信息是否错误或被删除！";
						log.error(errMsg);
						model.addAttribute("errorMessage", errMsg);
					}
					listSelectedNcCodeFormMap.add(listNcCodeFormMap.get(0));
				}
			}
		}

		// 2.未分配不良代码组的不良代码列表
		NcCodeFormMap ncCodeFormMap2 = new NcCodeFormMap();
		ncCodeFormMap2.put("where", " where site_id ='" + siteId + "'  order by create_time");
		List<NcCodeFormMap> listAllNcCodeFormMap = baseMapper.findByWhere(ncCodeFormMap2);
		NcCodeGroupRelationFormMap ncCodeGroupRelationFormMap = new NcCodeGroupRelationFormMap();
		ncCodeGroupRelationFormMap.put("where", " where site_id ='" + siteId + "' ");
		List<NcCodeGroupRelationFormMap> listAllNcCodeGroupRelationFormMap = baseMapper
				.findByWhere(ncCodeGroupRelationFormMap);
		// 已被分配不良代码组的不良代码列表
		List<String> listHasGroupNcCodeId = new ArrayList<String>();
		for (int i = 0; i < listAllNcCodeGroupRelationFormMap.size(); i++) {
			NcCodeGroupRelationFormMap map = listAllNcCodeGroupRelationFormMap.get(i);
			String ncCodeId = map.getStr("nc_code_id");
			listHasGroupNcCodeId.add(ncCodeId);
		}
		List<NcCodeFormMap> listUnSelectedNcCodeFormMap = new ArrayList<NcCodeFormMap>();
		for (int i = 0; i < listAllNcCodeFormMap.size(); i++) {
			NcCodeFormMap map = listAllNcCodeFormMap.get(i);
			String id = map.getStr("id");
			if (!listHasGroupNcCodeId.contains(id)) {
				listUnSelectedNcCodeFormMap.add(map);
			}
		}

		model.addAttribute("unSelectedNcCodeList", listUnSelectedNcCodeFormMap);
		model.addAttribute("selectedNcCodeList", listSelectedNcCodeFormMap);
	}

	/**
	 * 保存不良代码组
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("saveNcCodeGroup")
	@SystemLog(module = "不良代码组维护", methods = "不良代码组维护-保存不良代码组") // 凡需要处理业务逻辑的.都需要记录操作日志
	public String saveNcCodeGroup() {
		NcCodeGroupFormMap ncCodeGroupFormMap = getFormMap(NcCodeGroupFormMap.class);
		ncCodeGroupFormMap.put("create_time", DateUtils.getStringDateTime());
		ncCodeGroupFormMap.put("create_user", ShiroSecurityHelper.getCurrentUsername());
		ncCodeGroupFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
		try {
			ncCodeGroupService.saveNcCodeGroup(ncCodeGroupFormMap);
		} catch (BusinessException e) {
			log.error(e.getMessage());
			return ResponseHelp.responseErrorText(e.getMessage());
		}
		return ResponseHelp.responseText();
	}

	/**
	 * 检索不良代码组
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("queryNcCodeGroup")
	public String queryNcCodeGroup(Model model, HttpServletRequest request) {
		String siteId = ShiroSecurityHelper.getSiteId();
		String ncCodeGroupNo = request.getParameter("nc_code_group_no");
		// 1.查询不良代码组的基本信息
		NcCodeGroupFormMap ncCodeGroupFormMap = new NcCodeGroupFormMap();
		ncCodeGroupFormMap.put("nc_code_group_no", ncCodeGroupNo);
		ncCodeGroupFormMap.put("site_id", siteId);
		List<NcCodeGroupFormMap> listNcCodeGroupFormMap = baseMapper.findByNames(ncCodeGroupFormMap);
		if (!ListUtils.isNotNull(listNcCodeGroupFormMap)) {
			String errMessage = "未检索到不良代码组编号为：" + ncCodeGroupNo.toUpperCase() + "的信息";
			log.error(errMessage);
			model.addAttribute("res", findByRes());
			model.addAttribute("errorMessage", errMessage);
			getNcCodeBindData(model, siteId, "");
			handlePageRes(model,request);
			return ncCodeGroupMaintenanceUrl;
		}

		ncCodeGroupFormMap = listNcCodeGroupFormMap.get(0);
		model.addAttribute("ncCodeGroupFormMap", ncCodeGroupFormMap);

		String ncCodeGroupId = ncCodeGroupFormMap.getStr("id");
		// 2.查询不良代码组的不良代码信息
		getNcCodeBindData(model, siteId, ncCodeGroupId);

		model.addAttribute("successMessage", "检索成功");
		handlePageRes(model,request);
		return ncCodeGroupMaintenanceUrl;
	}

	/**
	 * 删除不良代码组
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("delNcCodeGroup")
	public String delNcCodeGroup(Model model, HttpServletRequest request) {
		String ncCodeGroupId = request.getParameter("nc_code_group_id");
		String siteId = ShiroSecurityHelper.getSiteId();
		try {
			if (StringUtils.isEmpty(ncCodeGroupId)) {
				throw new BusinessException("操作失败，参数不能为空！");
			}
			ncCodeGroupService.delNcCodeGroup(ncCodeGroupId);
		} catch (BusinessException e) {
			String errMessage = e.getMessage();
			log.error(errMessage);
			model.addAttribute("res", findByRes());
			model.addAttribute("errorMessage", errMessage);
			getNcCodeBindData(model, siteId, "");
			handlePageRes(model,request);
			return ncCodeGroupMaintenanceUrl;
		}
		model.addAttribute("res", findByRes());
		model.addAttribute("successMessage", "删除不良代码成功");
		getNcCodeBindData(model, siteId, "");
		handlePageRes(model,request);
		return ncCodeGroupMaintenanceUrl;
	}

}